<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Request;
use think\Validate;
use think\Db;

class Onlineclassroom extends Api
{
    // 不需要登录和权限校验
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    
    /**
     * 微信小程序用户申请加入空中课堂
     */
    public function applyToClassroom(Request $request)
    {
        // 获取请求数据
        $data = $request->post();
        $apply_reason= $request->post('apply_reason');
        $user = $this->auth->getUser(true);
        $data['user_id']=$user['uid'];
        $classroom_id = model("app\admin\model\User")->getClassroomByUserId($user['uid']);
        if(!$user){
            return json(['code' => 401, 'msg' => '请先登录']);
        }
        // 验证必要字段
        $validate = new Validate();
        $validate->rule([
            'user_id' => 'require|number'
        ]);
        
        // 验证数据
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 检查是否已申请
        $existing = Db::name('online_classroom_user')
            ->where(['user_id' => $user['uid']])
            ->find();
            
        if ($existing) {
            return json(['code' => 409, 'msg' => '您已申请加入该课堂']);
        }
        $apply_reason=$apply_reason??"希望能够参与空中课堂学习，提升自己的专业技能";
        // 添加申请记录
        $applyData = [
            'classroom_id' => $classroom_id,
            'user_id' => $user['uid'],
            'status' => 0, // 0-待审核 1-通过 2-拒绝
            'apply_reason' =>$apply_reason,
            'join_time' => time()
        ];
        
        $result = Db::name('online_classroom_user')->insert($applyData);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '申请已提交，请等待审核']);
        } else {
            return json(['code' => 500, 'msg' => '申请失败，请重试']);
        }
    }
}